package logic

import (
	"context"
	"course-admin/model"
	"course-admin/pkg"
	"errors"
	"fmt"
	"math/rand"
	"time"

	"course-admin/userrpc/internal/svc"
	"course-admin/userrpc/userrpc"

	"github.com/zeromicro/go-zero/core/logx"
)

type RegisterLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewRegisterLogic(ctx context.Context, svcCtx *svc.ServiceContext) *RegisterLogic {
	return &RegisterLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

// 注册
func (l *RegisterLogic) Register(in *userrpc.RegisterRequest) (*userrpc.RegisterResponse, error) {
	// todo: add your logic here and delete this line
	var findUser model.User

	if err := findUser.FindUserByMobile(model.DB, in.Mobile); err != nil {
		return nil, err
	}
	if findUser.ID != 0 {
		return nil, errors.New("已注册")
	}
	user := model.User{
		Mobile:   in.Mobile,
		Password: pkg.Str(in.Password),
		HeadImg:  "https://ts4.tc.mm.bing.net/th/id/OIP-C.KpKXw2sWdqAD5k0M2hgfSwAAAA?rs=1&pid=ImgDetMain&o=7&rm=3",
		Nickname: fmt.Sprintf("wx%v%v", time.Now().Unix(), rand.Intn(100000000)),
	}

	if err := user.Register(model.DB); err != nil {
		return nil, errors.New("注册失败")
	}

	return &userrpc.RegisterResponse{
		UserId: int64(user.ID),
	}, nil
}
